import UIKit

class Toast {
    static func show(message: String, duration: TimeInterval = 2.0, in view: UIView? = nil) {
        guard let container = view ?? UIApplication.shared.keyWindow else { return }
        
        // 创建 Toast 视图
        let toastView = UIView()
        toastView.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        toastView.alpha = 0
        toastView.layer.cornerRadius = 8
        toastView.clipsToBounds = true
        
        // 添加文字标签
        let label = UILabel()
        label.textColor = .white
        label.textAlignment = .center
        label.numberOfLines = 0
        label.text = message
        label.font = UIFont.systemFont(ofSize: 14)
        
        toastView.addSubview(label)
        container.addSubview(toastView)
        
        // 布局约束
        label.translatesAutoresizingMaskIntoConstraints = false
        toastView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: toastView.leadingAnchor, constant: 16),
            label.trailingAnchor.constraint(equalTo: toastView.trailingAnchor, constant: -16),
            label.topAnchor.constraint(equalTo: toastView.topAnchor, constant: 8),
            label.bottomAnchor.constraint(equalTo: toastView.bottomAnchor, constant: -8),
            
            toastView.leadingAnchor.constraint(greaterThanOrEqualTo: container.leadingAnchor, constant: 20),
            toastView.trailingAnchor.constraint(lessThanOrEqualTo: container.trailingAnchor, constant: -20),
            toastView.centerXAnchor.constraint(equalTo: container.centerXAnchor),
            toastView.bottomAnchor.constraint(equalTo: container.safeAreaLayoutGuide.bottomAnchor, constant: -30)
        ])
        
        // 动画显示
        UIView.animate(withDuration: 0.3, animations: {
            toastView.alpha = 1
        }) { _ in
            // 定时隐藏
            UIView.animate(withDuration: 0.3, delay: duration, options: .curveEaseOut, animations: {
                toastView.alpha = 0
            }) { _ in
                toastView.removeFromSuperview()
            }
        }
    }
}
